import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { DialogService, DValidateRules, FormLayout, TableWidthConfig } from 'ng-devui';
import { PurchaseRequiredOrder } from 'src/app/@core/data/purchase';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { environment } from 'src/environments/environment';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';

@Component({
  selector: 'app-purchase-requirement-add',
  templateUrl: './purchase-requirement-add.component.html',
  styleUrls: ['./purchase-requirement-add.component.scss']
})
export class PurchaseRequirementAddComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl
  layoutDirection: FormLayout = FormLayout.Horizontal;
  purchaseRequired: PurchaseRequiredOrder = {
    purchaseRequiredOrderId: null,//采购需求单ID
    advicePurchaseDate: null,//建议采购日期
    purchaseManName: '',// 申请人
    purchaseManId: 0,//申请人ID
    purchaseManNum: '', //申请员工号
    departmentName: '', //部门
    departmentId: 0, //部门ID
    departmentNum: '', //部门编号
  remark: '', //备注
  billCategory: undefined, // 单据类别
    purchaseRequiredNum: '', //采购需求单号
    status: '未开始审核', //状态
    isClosed: false, //是否结案
    createDate: null, //制单日期
    creator: '', //制单人
    files: [], //附件
    purchaseRequiredOrderParts: [
      {
        purchaseRequiredOrderPartId: null, //物料行ID
        PROPpurchaseRequiredOrderId: null, //采购需求单ID
        partNum: '', //物料编号
        partUOM: '', //物料单位
        partName: '', //物料名称
        description: '', //物料描述
        partType: '', //规格型号
        image: '', //图片
        purchaseQuantity: 0, //申请采购数量
        orderedQuantity: 0, //已下单数量
        purchaseDate: null, //建议采购日期
        PROPSupplyId: 0, //建议供应商ID
        supplyName: '', //建议供应商名称
        supplyNum: '', //建议供应商编号
        PROPPartId: 0, //物料外键ID
        note: '' //备注
        ,
        isInspection: false
      }
    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '200px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '规格型号',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '申请采购数量',
      width: '170px'
    },
    {
      field: '建议采购时间',
      width: '200px'
    },
    {
      field: '建议供应商',
      width: '200px'
    },
    {
      field: '是否检验',
      width: '200px'
    },
    {
      field: '备注',
      width: '170px'
    }
  ]
  taxRate: number = 13
  customerContact: any
  loadData: boolean
  purchaseRequiredRules: { [key: string]: DValidateRules } = {
    purchaseRequiredNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*采购需求单单号不能为空' },
        { minlength: 2, message: '*采购需求单单号长度至少为2' },
        { maxlength: 40, message: '*采购需求单单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*采购需求单单号不能包含空格' }
      ]
    },
    purchaseManName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*申请人不能为空' },
      ]
    },
    advicePurchaseDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*建议申请时间不能为空' },
      ]
    },
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料不能为空' },
      ]
    },
    purchaseDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*建议采购时间不能为空' },
      ]
    },
    purchaseQuantity: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*建议采购数量不能为空' },
      ]
    }
  }
  fujianNumber: any = 0
  defaultData:Date
  options = [
    { label: '检验', value: true },
    { label: '不检验', value: false }
  ]
  billCategoryOptions = [
    { label: '辅料', value: '辅料' },
    { label: '辅材', value: '辅材' },
    { label: '原料', value: '原料' },
    { label: '食材', value: '食材' },
  ]
  constructor(private DialogService: DialogService, private Router: Router, private UserService: UserService, private PurchaseService: PurchaseService, private EncodeRulesService: EncodeRulesService,private ReviewFlowService:ReviewRolesService) { }
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule('采购需求单','采购需求单').subscribe((res: any) => {
      this.purchaseRequired.purchaseRequiredNum = res
    })
    const userinfoString = localStorage.getItem('userinfo')
    if (userinfoString) {
      this.purchaseRequired.creator = JSON.parse(userinfoString).username
    }
  }
  selectMaterial(rowItem: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择物料',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {

      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.PROPPartId = results.modalContentInstance.selectData.partId;
            rowItem.partNum = results.modalContentInstance.selectData.partNum;
            rowItem.partName = results.modalContentInstance.selectData.partName;
            rowItem.partUOM = results.modalContentInstance.selectData.partUOM;
            rowItem.partType = results.modalContentInstance.selectData.partType;
            rowItem.image = results.modalContentInstance.selectData.fileURL
            rowItem.PROPSupplyId = results.modalContentInstance.selectData.supplyId
            rowItem.description = results.modalContentInstance.selectData.description
            rowItem.supplyName = results.modalContentInstance.selectData.supplyName
            rowItem.supplyNum = results.modalContentInstance.selectData.supplyNum
            rowItem.isInspection = results.modalContentInstance.selectData.isInspection
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  advicePurchaseDateChange() {
    this.defaultData = this.purchaseRequired.advicePurchaseDate;
    this.purchaseRequired.purchaseRequiredOrderParts.forEach((item) => {
            item.purchaseDate = this.defaultData;

    });
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  addRow() {
    this.purchaseRequired.purchaseRequiredOrderParts.push({
      purchaseRequiredOrderPartId: null, //物料行ID
      PROPpurchaseRequiredOrderId: null, //采购需求单ID
      partNum: '', //物料编号
      partUOM: '', //物料单位
      partName: '', //物料名称
      description: '', //物料描述
      partType: '', //规格型号
      image: null, //图片
      purchaseQuantity: 0, //申请采购数量
      orderedQuantity: 0, //已下单数量
      purchaseDate: this.defaultData, //建议采购日期
      PROPSupplyId: 0, //建议供应商ID
      supplyName: '', //建议供应商名称
      supplyNum: '', //建议供应商编号
      PROPPartId: 0, //物料外键ID
      note: '' //备注
      ,
      isInspection: false
    })
  }//添加行
  deleteRow(index: number) {
    this.purchaseRequired.purchaseRequiredOrderParts.splice(index, 1);
    if (this.purchaseRequired.purchaseRequiredOrderParts.length == 0) {
      this.addRow()
    }
  }//删除行
  isStartApproval: boolean = false
  isStartApprovalChange() {
    this.isStartApproval = true
  }
  submit($event: any) {
    this.purchaseRequired.createDate = new Date();
    if ($event.valid) {
        if (!this.validateSalesQuotation(this.purchaseRequired)) {
            return;
        }
        this.PurchaseService.addPurchaseRequirement(this.purchaseRequired).subscribe((res: any) => {
            if (this.isStartApproval) {
                this.ReviewFlowService.StartApprovalFlow('采购需求单审核流配置', [this.purchaseRequired.purchaseRequiredNum]).subscribe((data: any) => {
                    this.showToast('success', '成功', data);
                    setTimeout(() => {
                        this.Router.navigateByUrl('/pages/purchase/purchase-require');
                    }, 1000);
                },(error)=>{
                    this.showToast('warning', '失败', '单据创建成功，审批流程启动失败');
                    setTimeout(() => {
                      this.Router.navigateByUrl('/pages/purchase/purchase-require');
                  }, 1000);
                }
              );
            }else {
                this.showToast('success', '成功', '添加成功');
                setTimeout(() => {
                    this.Router.navigateByUrl('/pages/purchase/purchase-require');
                }, 1000);
            }
        }, (error) => {
            if (error.status == 404) {
                this.showToast('error', '失败', '服务器连接失败');
            } else {
                this.showToast('error', '失败', error.error);
            }
        });
    } else {
        this.showToast('warn', '错误', '请检查表单是否填写正确');
    }
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel() {
    this.Router.navigateByUrl('/pages/purchase/purchase-require')
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '采购需求附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: this.purchaseRequired.files
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseRequired.files.push(results.modalContentInstance.urls);
            this.fujianNumber = this.purchaseRequired.files.length

            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  validateSalesQuotation(purchaseRequired: PurchaseRequiredOrder): boolean {
    for (const [index, item] of purchaseRequired.purchaseRequiredOrderParts.entries()) {
      if (!item.partNum) {
        this.showToast('warn', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.purchaseQuantity <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行申请采购数量必须大于0`);
        return false;
      }
      if (!item.purchaseDate) {
        this.showToast('warn', '错误', `第${index + 1}行建议采购时间不能为空`);
        return false;
      }
    }
    return true;
  } // 所有验证通过
  selectUser() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择申请人',
      content: SelectUserComponent,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseRequired.purchaseManName = results.modalContentInstance.selectData.name;
            this.purchaseRequired.purchaseManId = results.modalContentInstance.selectData.id;
            this.purchaseRequired.purchaseManNum = results.modalContentInstance.selectData.employeeCode;
            this.UserService.GetDepartmentById(results.modalContentInstance.selectData.departmentId).subscribe((res: any) => {
              this.purchaseRequired.departmentName = res.name;
              this.purchaseRequired.departmentId = res.departmentId;
              this.purchaseRequired.departmentNum = res.departmentCode;

            })
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectDepartment() {
    if (!this.purchaseRequired.purchaseManId) {
      this.showToast('warn', '请选择申请人', '请选择申请人')
    }
  }
  selectsupply(rowItem:any, dialogtype?:string){
    const results = this.DialogService.open({
      id: 'Addselectsupply',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择供应商',
      content: SelectSupplierComponent,
      dialogtype: dialogtype,
      onClose: () => {

      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.PROPSupplyId = results.modalContentInstance.selectData.supplyId
            rowItem.supplyName = results.modalContentInstance.selectData.supplyChineseName
            rowItem.supplyNum = results.modalContentInstance.selectData.supplyNum
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
